import {View, Text} from "@tarojs/components";
import {orderType} from "@/types";
import "./index.scss"
import {ToPage} from "@/utils";
import user from "@/store/user";
import {Checkbox, Button, Input} from '@taroify/core';
import React, {useState} from "react";
import Taro from "@tarojs/taro";
import SubmitModal from "@/pages/order/modal";
import {ShowToast} from "@/utils";
import http from "@/request";

interface OrderListProps {
    orderList: orderType[];
    btns?: string[];
    showCheckbox?: boolean;
    selectedOrders?: string[];
    onSelectChange?: (selectedIds: string[]) => void;
    onUpdate?: (order: orderType) => void;
}

const OrderList: React.FC<OrderListProps> = ({
    orderList,
    btns = ['dispatch', 'reschedule', 'success', 'fail', 'copy', 'comment'],
    showCheckbox = false,
    selectedOrders: externalSelectedOrders,
    onSelectChange,
    onUpdate
}) => {
    const [internalSelectedOrders, setInternalSelectedOrders] = useState<string[]>([]);

    // 使用外部传入的 selectedOrders 或内部状态
    const selectedOrders = externalSelectedOrders || internalSelectedOrders;

    const markSuccess = (order: orderType) => {
        Taro.setStorageSync('success-order-info',order)
        ToPage('/pages/order-success/index')
    }

    const [showCommentModal, setShowCommentModal] = useState<boolean>(false);
    const [currentOrder, setCurrentOrder] = useState<orderType | null>(null);
    const [commentInput, setCommentInput] = useState<string>('');

    const showCommentAodal = (item: orderType) => {
        setCurrentOrder(item);
        setCommentInput(item.orderComment || '');
        setShowCommentModal(true);
    }

    const handleCommentConfirm = async () => {
        if (!currentOrder) return;

        try {
            // 调用API更新订单备注
            await http.post('/disp/biz/order/updateOrderComment', {
                id: currentOrder.id,
                orderComment: commentInput
            });

            ShowToast('备注更新成功', 'success');
            setShowCommentModal(false);
            setCurrentOrder(null);
            setCommentInput('');
            onUpdate && onUpdate(currentOrder)
            // 可以在这里添加回调来刷新订单列表
            // 或者通过props传递刷新函数

        } catch (error) {
            ShowToast('备注更新失败', 'error');
            console.error('更新备注失败:', error);
        }
    }

    const handleCommentCancel = () => {
        setShowCommentModal(false);
        setCurrentOrder(null);
        setCommentInput('');
    }

    const toOperatePage = (type: string, item: any) => {
        if (['dispatch', 'reschedule', 'fail'].includes(type)) {
            ToPage(`/pages/order-change/index?id=${item.id}&teamId=${item.bizTeamId}&type=${type}`)
        }
    }
    const copyOrder = (item) => {
        if (Taro.setClipboardData) {
            Taro.setClipboardData({ data:
`业务团队：${item.bizTeamName}
客户姓名：${item.customerName}
客户电话：${item.customerPhone}
套餐：${item.comboName}
礼物：${item.giftName}
业务员：${item.bizTeamUsername}
工号：${item.bizTeamUserCode}
坐席团队：${item.seatTeamName}
可办理日期：${item.appointmentProcessingDate}
备注：${item.orderComment}
地址：${item.fullAddressName}`
            });
        } else {
            Taro.showModal({
                title: '提示',
                content: '当前微信版本过低，请升级后使用'
            });
        }
    }


    const copyAddress = (item) => {
        if (Taro.setClipboardData) {
            Taro.setClipboardData({ data: item.fullAddressName });
        } else {
            Taro.showModal({
                title: '提示',
                content: '当前微信版本过低，请升级后使用'
            });
        }
    }

    const btnObj = {
        dispatch: (item) => (<Button size={"small"} onClick={() => toOperatePage('dispatch', item)}>派单</Button>),
        success: (item) => (<Button size={"small"} color="success" onClick={() => markSuccess(item)}>成功</Button>),
        comment: (item) => (<Button size={"small"} color="success" onClick={() => showCommentAodal(item)}>更新备注</Button>),
        reschedule: (item) => (<Button size={"small"} color="warning" onClick={() => toOperatePage('reschedule', item)}>改约</Button>),
        fail: (item) => (<Button size={"small"} color="danger" onClick={() => toOperatePage('fail', item)}>未成功</Button>),
        copy: (item) => (<Button size={"small"} color="info" onClick={() => copyOrder(item)}>复制</Button>),
    }

    const operateMap = {
        SeatAssignment: ['dispatch', 'copy'],
        TeamAssignment: ['dispatch', 'reschedule', 'success', 'fail', 'copy'],
        OrderReschedule: ['dispatch', 'reschedule', 'success', 'fail', 'copy'],
        Success: ['success', 'copy'],
        Fail: ['dispatch', 'copy', 'comment']
    }

    const getBtnsArray = (item) => {
        const {status, bizTeamUserCode } = item
        const ruleKeys: string[] = ['copy', 'comment']
        if (user.info?.teamLeaderFlag === 'T') {
            ruleKeys.push('dispatch')
            if (user.info?.userCode === bizTeamUserCode) {
                // 管理员自己的订单
                ruleKeys.push('reschedule', 'success', 'fail')
            }
        } else {
            ruleKeys.push('reschedule', 'success', 'fail')
        }
        // ruleKeys.push('copy')
        return (operateMap[status] || []).filter(key => {
            return btns.includes(key)
        }).filter(key => {
            return ruleKeys.includes(key)
        })
    }

    const handleOrderSelect = (orderId: string) => {
        const newSelected = selectedOrders.includes(orderId)
            ? selectedOrders.filter(id => id !== orderId)
            : [...selectedOrders, orderId];

        if (externalSelectedOrders) {
            onSelectChange?.(newSelected);
        } else {
            setInternalSelectedOrders(newSelected);
            onSelectChange?.(newSelected);
        }
    };

    // const handleSelectAll = (checked: boolean) => {
    //     const newSelected = checked
    //         ? orderList.map(order => String(order.id || ''))
    //         : [];
    //     setSelectedOrders(newSelected);
    //     onSelectChange?.(newSelected);
    // };
    const makePhoneCall = (phoneNumber) => {
        Taro.makePhoneCall({
            phoneNumber,
            success: () => console.log("拨号成功"),
            fail: (err) => console.error("拨号失败", err)
        });
    }

    return (<View className="info-card">
        {/* {showCheckbox && (
            <View className="order-list-header">
                <Checkbox
                    checked={selectedOrders.length === orderList.length && orderList.length > 0}
                    onChange={handleSelectAll}
                >
                    全选
                </Checkbox>
            </View>
        )} */}
        {
            orderList.length ? orderList.map((item, index) => {
                return (
                    <View key={`${item.id || ''}${index}`} className="card-container">
                        <View className="order-header">
                            {showCheckbox && (
                                <Checkbox
                                    className="check-box"
                                    checked={selectedOrders.includes(String(item.id || ''))}
                                    onChange={() => handleOrderSelect(String(item.id || ''))}
                                />
                            )}
                            <Text className="order-id flex1">{item.orderNo}</Text>
                            {
                                !showCheckbox && (
                                    <Text className="order-status">{item.statusName}</Text>
                                )
                            }
                        </View>
                        <View className="order-customer">
                            客户信息：{item.customerName}
                            <Text className={'phone'} onClick={() => makePhoneCall(item.customerPhone)}>
                                <Text className={'iconfont icon-dianhua'}></Text>
                                <Text>{item.customerPhone}</Text>
                            </Text>
                        </View>
                        <View className="order-customer">套餐/礼物：{item.comboName} {item.giftName}</View>
                        <View className="order-customer">业务员：{item.bizTeamUserCode || '-'} {item.bizTeamUsername || '-'}</View>
                        <View className="order-customer">坐席团队：{item.seatTeamName || '-'}</View>
                        <View className="order-customer">可办理日期：{item.appointmentProcessingDate || '-'}</View>
                        <View className="order-customer">备注：{item.orderComment || '-'}</View>
                        <View className="order-customer">
                            地址：{item.fullAddressName || '-'}
                            <Text onClick={() => copyAddress(item)} className="copy-btn">复制</Text>
                        </View>
                        <View className="order-customer">更新时间：{item.updateTime || '-'}</View>
                        <View className="order-create-info">由{item.createUserName}于{item.createTime}创建</View>
                        {!showCheckbox && (
                            <View className="order-actions">
                                <View className="flex1"></View>
                                {
                                    getBtnsArray(item).map(btn => {
                                        return btnObj[btn] && btnObj[btn](item)
                                    })
                                }
                            </View>
                        )}
                    </View>
                )
            }) : <View className="no-data flex-column flex-center">
                    <View className="title">暂无数据</View>
                    <View className="tips font-size24">暂时没有查询到符合条件的数据</View>
                    <View className="bg-word text-bg-color">DISPATCH</View>
                </View>
        }

        {/* 备注弹窗 */}
        <SubmitModal
            open={showCommentModal}
            title="添加备注"
            onClose={handleCommentCancel}
            onOk={handleCommentConfirm}
            child={
                <View style={{ padding: '20px 0' }}>
                    <Input
                        placeholder="请输入备注内容"
                        value={commentInput}
                        onChange={(e) => setCommentInput(e.detail.value)}
                        style={{
                            width: '100%',
                            border: '1px solid #ddd',
                            borderRadius: '8rpx',
                            height: '60rpx',
                            lineHeight: '60rpx',
                        }}
                    />
                </View>
            }
        />
    </View>)
}

export default OrderList